/**
 *  *2010-5-2 上午12:17:25  add 
 */
package com.base.myproject.server.jbpm;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import org.jbpm.api.ExecutionService;
import org.jbpm.api.ProcessDefinition;
import org.jbpm.api.ProcessDefinitionQuery;
import org.jbpm.api.ProcessEngine;
import org.jbpm.api.ProcessInstance;
import org.jbpm.api.RepositoryService;
import org.jbpm.api.TaskQuery;
import org.jbpm.api.TaskService;
import org.jbpm.api.task.Task;

import com.base.myproject.client.jdbc.DataSet;
import com.base.myproject.server.jbpm.jpdl.JpdlModel;
import com.base.myproject.server.jbpm.jpdl.JpdlModelDrawer;
import com.base.myproject.server.tools.DataSetTool;

/**
 * @author Administrator
 *2010-5-2
 * javazgw@gmail.com
 * 获得流程下的所有实例
 * System.out.println( executionService.createProcessInstanceQuery().processDefinitionId(processDefinitions.get(0).getId()).list());
 * 获得所有流程
 * 	List<ProcessDefinition> processDefinitions = repositoryService
	    .createProcessDefinitionQuery().orderAsc( ProcessDefinitionQuery.PROPERTY_NAME).list();


 * 流程启动格式flowkey+"."+busicode+"."+icode   aa.6001.1001
 *
 */
public class WorkFlow {
	
	ProcessEngine processEngine;
	final static public int AGREE =1;
	final static public int DISAGREE =2;
	public WorkFlow()
	{
		init();
	}
	/**
	 * 初始化
	 */
	public void init()
	{
		//processEngine = new Configuration().setResource("resources/my.jbpm.cfg.xml").buildProcessEngine();
		processEngine = JbpmPE.getInstance().getPe();
	}
	
	public TaskService getTaskService() {
		return processEngine.getTaskService();
	}
	/**
	 * 部署新的业务流程
	 * @param resource
	 */
	public  void deploy(String resource)
	{
		RepositoryService repositoryService = processEngine.getRepositoryService();
		repositoryService.createDeployment().addResourceFromClasspath(resource).deploy();
		
	}
	/**
	 * 部署新的业务流程
	 * @param resource
	 */
	public  void deploy(File file)
	{
		RepositoryService repositoryService = processEngine.getRepositoryService();
		repositoryService.createDeployment().addResourceFromFile(file).deploy();
	}
	/**
	 * 开始一项新的流程
	 * process name="simple1" 根据此名字启动
	 * @return
	 */
	public ProcessInstance startflow(String flowkey,String bcode,String icode)
	{
		ExecutionService executionService = processEngine.getExecutionService();
		Map<String, String> variable = new HashMap<String, String>();
		variable.put("owner", bcode);
		variable.put("icode", icode);
		ProcessInstance processInstance  =executionService.startProcessInstanceByKey(flowkey, variable, bcode+"."+icode);
		
		return processInstance;
	}
	/**
	 * 根据流程号与内码查找流程成
	 * @param flowkey
	 * @param busicode
	 * @return
	 */
	public ProcessInstance findflow(String flowkey,String busicode,String icode)
	{
		ExecutionService executionService = processEngine.getExecutionService();
		ProcessInstance processInstance  =executionService.findProcessInstanceById(flowkey+"."+busicode+"."+icode);
		return processInstance;
	}
	
	/**
	 * 根据人员查找任务
	 * @param name
	 * @return
	 */
	
	public List<Task> findPersonalTasks(String name)
	{
		TaskService taskService = processEngine.getTaskService();
		 List<Task> tasks  = taskService.findPersonalTasks(name);
		 return tasks;
	}
	/**
	 * Map<String,Object> variables = new HashMap<String,Object>();
				variables.put("content", "to task2");
				variables.put("order", new Order("zgw"));
				wf.completetask("310005",variables);
	 * 完成任务
	 * @param id
	 * @param variables
	 */
	public  void completetask(String id,Map<String,Object> variables)
	{
		TaskService taskService = processEngine.getTaskService();

		 taskService.completeTask(id,variables);	
	}
	
	/**
	 * Map<String,Object> variables = new HashMap<String,Object>();
				variables.put("content", "to task2");
				variables.put("order", new Order("zgw"));
				wf.completetask("310005",variables);
	 * 完成任务
	 * @param id
	 * @param variables
	 */
	public  void completetask(String id, String costum, Map<String,Object> variables)
	{
		TaskService taskService = processEngine.getTaskService();

		 taskService.completeTask(id, costum, variables);	
	}
	/**
	 * 审批流程
	 * @param flowname
	 * @param busi
	 * @param icode
	 * @param userid
	 * @param id
	 * @param variables
	 * @param type
	 */
	public void completetask(String flowname,String busi,String icode,String userid,String id,Map<String,Object> variables,int type,String description)
	{
		TaskService taskService = processEngine.getTaskService();
		List<Task> tasks = taskService.createTaskQuery().processInstanceId(flowname+"."+busi+"."+icode).assignee(userid).list();
		for(Task t:tasks)
		{
			if(t.getId().equals(id))
				//审批通过
				if(type==AGREE)
				{
					 taskService.completeTask(id,variables);	
					 return;
				}
				//审批不通过
				else if(type==DISAGREE)
				{
					 processEngine.getExecutionService().endProcessInstance(flowname+"."+busi+"."+icode, "active");
					 return ;
				}
		}
		
		
	}
	/**
	 * 获得所有流程
	 * @return
	 */
	public List<ProcessDefinition> getAllProcess()
	{
		RepositoryService repositoryService = processEngine.getRepositoryService();
		List<ProcessDefinition> processDefinitions = repositoryService
	    .createProcessDefinitionQuery().orderAsc( ProcessDefinitionQuery.PROPERTY_NAME).list();
		return processDefinitions;
	}
	
	/**
	 * 获得所有流程
	 * @return
	 */
	public Task getTaskByProcessInstance(ProcessInstance instance)
	{
		TaskService taskService = processEngine.getTaskService();
		Task task = taskService.createTaskQuery().processInstanceId(instance.getId()).list().get(0);
		return task;
	}
	
	/**
	 * 获得processid的所有实例
	 * eg.processid=simple1-1
	 * @param processid
	 * @return
	 */
	public List<ProcessInstance> getAllProcessInstance(String processid)
	{
		ExecutionService executionService = processEngine.getExecutionService();
		
		return executionService.createProcessInstanceQuery().processDefinitionId(processid).list();

	}
	/**
	 * 获取用户对应的任务列表
	 * @param userid
	 * @return
	 */
	public DataSet getTasksByUserId(String userid)
	{
		String str = "select * from jbpm4_task task   left join jbpm4_participation pt on task.DBID_=pt.TASK_    where task.ASSIGNEE_='"+userid+"' or ( pt.TYPE_ = 'candidate' and (pt.USERID_='"+userid+"')   or pt.GROUPID_ in ('"+userid+"')) ";
		DataSetTool dst = new DataSetTool();
		return dst.getDataSet(str);
	}
	
	/**
	 * 根据业务编码，内码，审批人，查找任务
	 * @param busi
	 * @param icode
	 * @param userid
	 * @return
	 */
	public DataSet getTasksByBusi_Userid(String flowname,String busi,String icode,String userid)
	{
		String str = "select * from jbpm4_task task   left join jbpm4_participation pt on task.DBID_=pt.TASK_    where (task.ASSIGNEE_='"+userid+"' or ( pt.TYPE_ = 'candidate' and (pt.USERID_='"+userid+"')   or pt.GROUPID_ in ('"+userid+"')) )and task.execution_id_='"+flowname+"."+busi+"."+icode+"'";
		DataSetTool dst = new DataSetTool();
		return dst.getDataSet(str);
	}
	/**
	 * 列举流程下活动的任务
	 * @param flowname
	 * @param busi
	 * @param icode
	 * @return
	 */
	public List<Task> getTasksByBusi(String flowname,String busi,String icode)
	{
		return getTasksByBusi(flowname+"."+busi+"."+icode);
	}
	
	public void makeFlowImage(File f,String imagename) throws Exception {

		InputStream inputStream = new FileInputStream(f);
		JpdlModel jpdlModel = new JpdlModel(inputStream);
	
		ImageIO.write(new JpdlModelDrawer().draw(jpdlModel), "png", new File(
				imagename));

	}
	/**
	 * 列举流程下活动的任务
	 * @param flowname
	 * @return
	 */
	public List<Task> getTasksByBusi(String flowname)
	{
		return getTasksByBusi_userid(flowname,null);
	}
	/**
	 * 列举流程下活动的任务,根据人员查找
	 * @param flowname
	 * @param userid
	 * @return
	 */
	public List<Task> getTasksByBusi_userid(String flowname ,String userid)
	{
		TaskService taskService = processEngine.getTaskService();
		if(userid!=null)
		return taskService.createTaskQuery().processInstanceId(flowname).assignee(userid).list();
		else
			return taskService.createTaskQuery().processInstanceId(flowname).list();
	}
	
	/**
	 * 使用默认api操作
	 * @param flowname
	 * @param busi
	 * @param icode
	 * @param userid
	 * @return
	 */
	public List<Task>  getTasksByBusi_Userid2(String flowname,String busi,String icode,String userid)
	{
		TaskService taskService = processEngine.getTaskService();
		TaskQuery qt = taskService.createTaskQuery();
		qt.assignee(userid);
		//qt.candidate(userid);
		return qt.processInstanceId(flowname+"."+busi+"."+icode).list();
		
	}
}
